package financeData;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.StringTokenizer;

public class yahooHistorical {


	public ArrayList<ArrayList<String>> getData(ArrayList<String> tickers)
	{
		
		ArrayList<ArrayList<String>> output = new ArrayList<ArrayList<String>>();
		Iterator<String> iterator = tickers.iterator();
		String x = "";
		int tickerCounter = 0;
		while(iterator.hasNext())
		{
			x = x + iterator.next() + ",";
			tickerCounter = tickerCounter + 1;
			if(tickerCounter > 150)
			{
				System.out.println("tickerList: " + x.substring(1,x.length()));
				webRequest(output,x.substring(1,x.length()));
				tickerCounter = 0;				
			}
		}
		if(tickerCounter > 0)
		{
			System.out.println("tickerList: " + x.substring(1,x.length()));
			webRequest(output,x.substring(1,x.length()));
		}
		return output;
	}
	
	private void webRequest(ArrayList<ArrayList<String>> outputData, String tickers)
	{
		String urlStart = "http://download.finance.yahoo.com/d/quotes.csv?s=";
		String urlEnd = "&f=s0v0a2f6s7c8i5o0p0d1l1k1k3t1l0a0b2a5b0b3b6k0j0h0g0m0m2l2l3x0d2c4s6j4d0y0r6r7e7e9e8e0r5r0r2b4p6j2t8j1j3&e=.csv";
		try
		{
			URL website = new URL(urlStart + tickers + urlEnd);
	        URLConnection yc = website.openConnection();
	        BufferedReader in = new BufferedReader(new InputStreamReader(
	                                    yc.getInputStream()));
	        String inputLine = "";
	        while ((inputLine = in.readLine()) != null) 
	        {
	            //inputLine
	        	ArrayList<String> x = new ArrayList<String>();
	        	StringTokenizer st = new StringTokenizer(inputLine,",");
	            while (st.hasMoreTokens()) {
	                x.add(st.nextToken());
	            }
	        	outputData.add(x);
	        }
	        in.close();
		}catch(IOException e) {
		    System.err.println("Caught IOException: " + e.getMessage());
		}
	}
}
